<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="90px">
            <el-row :gutter="24">
                <el-col :span="3" v-hasPermi="['machine:list:town']">
                    <el-form-item prop="townName" label-width="40px" style="margin:0">
                        <el-select placeholder="全部乡" v-model="queryParams.townName" @change="handleQueryTown" clearable
                            :style="{ width: '100%' }" size="small">
                            <el-option v-for="item in townOptions" :key="item.label" :label="item.label"
                                :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4" v-hasPermi="['machine:list:town']">
                    <el-form-item prop="villageName" label-width="40px" style="margin:0">
                        <el-select placeholder="全部村" v-model="queryParams.villageName" @change="handleQuery" size="small"
                            clearable :style="{ width: '100%' }">
                            <el-option v-for="item in villageOptions" :key="item.label" :label="item.label"
                                :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="16" v-hasPermi="['machine:list:village']">
                    <el-form-item prop="villageName" label-width="20px" style="margin:0">
                        <el-select placeholder="全部村" v-model="queryParams.villageName" @change="handleQuery" size="small" v-show="!isAdmin"
                            clearable :style="{ width: '100%' }">
                            <el-option v-for="item in villageOptions" :key="item.label" :label="item.label"
                                :value="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8" style="float:right;margin: 0;">
                    <el-form-item prop="year" label-width="40px" style="float:right;">
                        <el-select v-model="queryParams.year" :style="{ width: '100%' }">
                            <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="身份证号码" prop="idCard">
                        <el-input v-model="queryParams.idCard" placeholder="请输入身份证号码" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="一卡通号码" prop="bankCard">
                        <el-input v-model="queryParams.bankCard" placeholder="请输入一卡通号码" clearable size="small"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6" style="float:right;margin: 0;">
                    <el-form-item label="补贴类型" prop="appType" style="float:right;">
                        <el-select v-model="queryParams.appType" @change="handleQuery" size="small"
                            :style="{ width: '100%' }">
                            <el-option v-for="item in subsidyOptions" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-col>
            </el-row>

        </el-form>

        <el-table v-loading="loading" fit :data="list.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
            style="width: 100%;">
            <el-table-column label="工单编号" align="center" prop="appNum" />
            <el-table-column label="申请人" align="center" prop="appyBy" width="120" />
            <el-table-column label="身份证号码" align="center" prop="idCard" />
            <el-table-column label="一卡通号码" align="center" prop="bankCard" />
            <el-table-column label="补贴类型" align="center" prop="machineName" />
            <el-table-column label="申请时间" align="center" prop="submitDate">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.submitDate, '{y}') }}年</span>
                </template>
            </el-table-column>

            <el-table-column label="补贴金额" align="center" prop="moneySub" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleApply(scope.row)">查看</el-button>
                    <el-button size="mini" type="text" v-hasPermi="['machine:sift:village']"
                        @click="handleReg(scope.row)">查看核实表</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" />

    </div>
</template>
  
<script>
import { listComplieHandle } from "@/api/machinery/compliehandle";
import { listStrativeArea } from "@/api/subsidy/strativeArea";
import { checkRole, checkPermi } from '@/utils/permission'

export default {
    name: "Compile",

    data() {
        const now = new Date();
        return {
            year: now.getFullYear(),
            curyear: now.getFullYear() - 1,
            // 遮罩层
            loading: true,
            isAdmin:false,
            // 总条数
            total: 0,
            // 表格数据
            list: [],
            pageNum: 1,
            pageSize: 10,

            title: '',
            form: {},
            townOptions: [],
            villageOptions: [],

            dialog: false,
            loading: false,
            isDisabled: true,  // 控制驳回是否禁用输入

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                appType: '农用机车',
                appNum: undefined,
                idCard: undefined,
                bankCard: undefined,
                villageName: undefined,
                townName: undefined,
                staName: '滴道区',
                status: '已完成',
                year: new Date().getFullYear(),
            },
            subsidyOptions: [{
                "label": "农用机车",
                "value": "农用机车"
            }, {
                "label": "农用配套机具",
                "value": "农用配套机具"
            }],
        };
    },
    created() {
        this.role = this.$store.state.user.roles[0];
        console.log("当前登录角色", this.role)

        if(this.role == 'admin'){
            this.isAdmin = true;
        }

        if (this.$store.state.user.user.villageName) {
            this.queryParams.villageName = this.$store.state.user.user.villageName;
        }

        if (this.role == 'townNongji') {
            this.townName = this.$store.state.user.user.townName;
            this.queryParams.townName = this.townName
            console.log("当前登录角色乡名字", this.townName)
            // listStrativeArea({ townName: this.townName }).then(response => {
            //     console.log("村列表数据展示", response[0].children[0].children)
            //     this.villageOptions = response[0].children[0].children;
            //     if (this.villageOptions.length > 0) {
            //         this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
            //         // 触发后续查询（可选）
            //         this.handleQuery(); // 如果你想在默认选中后立即查询
            //     }
            // })
        }

        if (this.role == 'districtNongji' || this.role=='admin' ) {
            this.straName = '滴道区'
            this.queryParams.straName = this.straName
            listStrativeArea({ departmentName: '滴道区' }).then(response => {
                this.townOptions = response[0]?.children?.filter(item => item.type === 'town') || [];
                if (this.townOptions.length > 0) {
                    this.queryParams.townName = this.townOptions[0].label; // 或 .value，看你要绑定哪个
                    this.updateVillageOptions()
                    this.handleQuery(); // 如果你想在默认选中后立即查询
                }
            })
        }
        this.getList();
    },
    computed: {
        // 生成年份选项，例如从当前年份往前推10年，往后推10年
        yearOptions() {
            const currentYear = new Date().getFullYear();
            const years = [];
            for (let i = currentYear - 10; i <= currentYear + 10; i++) {
                years.push(i);
            }
            return years;
        },
    },
    methods: {
        checkRole,
        handleApply(row) {
            console.log("查询", row)
            let path = '';
            if (checkRole(['district', 'districtNongji'])) {
                path = '/machinery/compliehandle/registration';
            } else if (checkRole(['townNongji'])) {
                path = '/machinery/compliehandle/application';
            } else {
                this.$modal.msgError(`未赋予权限`)
                path = '/machinery/compliehandle';
            }
            if (path) {
                this.$router.push({
                    path,
                    query: { id: row.id, node: row.node, status: row.statusShow, readonly: true }
                });
            }
        },
        handleReg(row) {
            this.$router.push({
                path: '/machinery/compliehandle/registration',
                query: { id: row.id, node: row.node }
            });
        },
        updateVillageOptions() {
            // 清空当前村庄选择
            this.queryParams.villageName = '';

            if (!this.queryParams.townName) {
                this.villageOptions = [];
                return;
            }

            // 从 townOptions 中找到选中的乡镇
            const selectedTown = this.townOptions.find(town => town.label === this.queryParams.townName);

            // 设置村庄选项为其 children
            this.villageOptions = selectedTown?.children || [];
            console.log("村选项", this.villageOptions)
            // 如果有村庄，自动选中第一个
            // if (this.villageOptions.length > 0) {
            //     this.queryParams.villageName = this.villageOptions[0].label; // 或 .value，看你要绑定哪个
            //     // 触发后续查询（可选）
            //     this.handleQuery(); // 如果你想在默认选中后立即查询
            // }
        },

        // 当乡镇选择变化时触发
        handleQueryTown() {
            console.log("当前搜索条件", this.queryParams)
            this.handleQuery();
            this.updateVillageOptions();

            // 其他查询逻辑（如提交表单、刷新列表等）
        },

        getList() {
            this.loading = true;
            console.log("查询条件2", this.queryParams)
            listComplieHandle(this.queryParams).then(response => {
                this.list = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },

        // 表单重置
        reset() {
            this.queryParams = {
                idCard: undefined,
                bankCard: undefined,
                straName: '滴道区',
                villageName: undefined,
                townName: undefined,
                status: undefined,
                year: undefined,
            };
            this.resetForm("queryParams");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.pageNum = 1;
            this.getList();
        },

        handleReg(row) {
            this.reset();
            // this.loading = true;
            this.$router.push({
                path: '/machinery/compliehandle/registration',
                query: { id: row.id, node: row.node, readonly: true, }
            });
            // getSubsidyApplication(row.id).then(response => {
            //     this.loading = false;
            //     this.form = response.data;
            //     this.open = true;
            //     this.title = "申报信息";
            // });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
    }
};
</script>
  
<style scoped >
.app-container {
    background-color: white !important;
}

.card-container {
    background: white;
}

.el-scrollbar {
    height: 100px;
}

.el-select {
    .el-input__inner {
        width: 150px;
    }
}

.card-container {
    position: relative;
    width: 80%;
    align-items: center;
    margin-left: 10%;
    padding-bottom: 20px;
}

.infoDiv {
    width: 100%;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    padding-top: 20px;
}

.corner-label {
    position: absolute;
    top: 0;
    left: 0;
    background: #81B337;
    /* 背景色 */
    color: white;
    /* 文字颜色 */
    padding: 2px 8px;
    /* 内边距 */
    font-size: 20px;
    /* 字体大小 */
    border-radius: 4px;
    /* 圆角，左上角和右下角有圆角（根据需求调整） */
    transform: translate(-10%, -10%);
    /* 微调位置，使其覆盖在圆角上 */
    /* 如果需要，可以设置z-index */
    z-index: 1;
}

.demo-drawer__content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

}

::v-deep .demo-drawer .el-drawer__header {
    text-align: center;
    padding: 20px 0;
}


.demo-drawer__footer {
    align-items: center;
    text-align: center;
    margin-bottom: 20px;
}
</style>